﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ZGRemote.Common.Message;

namespace ZGRemote.Common.Processor
{
    public class MessageWaitAsync : MessageWaitBase
    {
        private TaskCompletionSource<MessageBase> tcs;

        protected bool disposedValue;

        private MessageBase message;
        public override MessageBase Message
        {
            get
            { return message; }
            set
            {
                if (value != null)
                {
                    message = value;
                    tcs.TrySetResult(message);
                }
            }
        }

        public MessageWaitAsync()
        {
            tcs = new TaskCompletionSource<MessageBase>();
        }

        public override async Task<MessageBase> WaitMessageAsync()
        {
            if(await Task.WhenAny(tcs.Task, Task.Delay(millisecondsTimeout)) == tcs.Task)
            {
                return await tcs.Task;
            }
            return null;
        }

        public override void Dispose()
        {
            if (disposedValue) return;
            tcs = null;
            message = null;
            disposedValue = true;
            GC.SuppressFinalize(this);
        }

    }
}
